package com.rainkaze.lifeharbor.tools.riddle;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.google.gson.Gson;
import com.rainkaze.lifeharbor.R;
import com.rainkaze.lifeharbor.databinding.ActivityToolRiddleBinding;
import com.rainkaze.lifeharbor.tools.riddle.model.RiddleData;
import com.rainkaze.lifeharbor.tools.riddle.model.RiddleResponse;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class RiddleActivity extends AppCompatActivity {

    private static final String TAG = "RiddleActivity";
    private static final String API_TOKEN = "LwExDtUWhF3rH5ib";
    private static final String API_BASE_URL = "https://v2.alapi.cn/api/riddle";
    private static final String RIDDLE_NUM = "1";

    private ActivityToolRiddleBinding binding;
    private OkHttpClient okHttpClient;
    private Gson gson;
    private Random randomGenerator;

    private String currentRiddleAnswer = "";
    private int hintLevel = 0; // 0: 无提示, 1: 长度提示, 2+: 字符提示
    private char[] revealedAnswerChars; // 用于存储已揭示的答案字符

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityToolRiddleBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        okHttpClient = new OkHttpClient();
        gson = new Gson();
        randomGenerator = new Random();

        setSupportActionBar(binding.toolbarRiddle);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        // “换一个谜语”按钮
        binding.buttonRefreshRiddle.setOnClickListener(v -> fetchRiddle());

        // “提交答案”按钮
        binding.buttonSubmitGuess.setOnClickListener(v -> checkUserGuess());

        // “获取提示”按钮
        binding.buttonGetHint.setOnClickListener(v -> provideHint());

        // “直接看谜底”按钮
        binding.buttonShowAnswerDirect.setOnClickListener(v -> showFullAnswer(true));

        fetchRiddle(); // 初始加载
    }

    private void fetchRiddle() {
        showLoadingState(true);
        resetGameState(); // 重置游戏状态

        HttpUrl.Builder urlBuilder = HttpUrl.parse(API_BASE_URL).newBuilder();
        urlBuilder.addQueryParameter("token", API_TOKEN);
        urlBuilder.addQueryParameter("num", RIDDLE_NUM);
        urlBuilder.addQueryParameter("page", String.valueOf(randomGenerator.nextInt(1000) + 1));

        String apiUrl = urlBuilder.build().toString();
        Log.d(TAG, "猜谜请求 URL: " + apiUrl);

        Request request = new Request.Builder().url(apiUrl).get().build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG, "网络请求失败: ", e);
                runOnUiThread(() -> {
                    if (binding == null) return;
                    showLoadingState(false);
                    binding.textViewRiddleContent.setText("网络请求失败，请检查网络。");
                    Toast.makeText(RiddleActivity.this, "网络错误: " + e.getMessage(), Toast.LENGTH_LONG).show();
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                final String responseBodyString;
                try (ResponseBody responseBody = response.body()) {
                    if (responseBody == null) {
                        Log.e(TAG, "API 响应体为空");
                        handleApiErrorOnUiThread("获取谜语失败: 服务器响应为空");
                        return;
                    }
                    responseBodyString = responseBody.string();
                }

                if (!response.isSuccessful()) {
                    Log.e(TAG, "API 请求未成功: " + response.message() + ", Code: " + response.code());
                    handleApiErrorOnUiThread("获取谜语失败 (HTTP " + response.code() + ")");
                    return;
                }

                Log.d(TAG, "谜语 API 响应: " + responseBodyString);
                runOnUiThread(() -> {
                    if (binding == null) return;
                    showLoadingState(false);
                    try {
                        RiddleResponse riddleResponse = gson.fromJson(responseBodyString, RiddleResponse.class);
                        if (riddleResponse != null && riddleResponse.getCode() == 200) {
                            List<RiddleData> riddleList = riddleResponse.getData();
                            if (riddleList != null && !riddleList.isEmpty()) {
                                RiddleData currentRiddle = riddleList.get(0);
                                setupNewRiddle(currentRiddle);
                            } else {
                                binding.textViewRiddleContent.setText("未能获取到谜语，请稍后再试。");
                                Toast.makeText(RiddleActivity.this, "没有谜语数据", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            handleBusinessError(riddleResponse, responseBodyString);
                        }
                    } catch (Exception e) {
                        Log.e(TAG, "JSON 解析或 UI 更新错误: ", e);
                        binding.textViewRiddleContent.setText("数据解析失败，请稍后再试。");
                        Toast.makeText(RiddleActivity.this, "数据处理错误", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    /**
     * 重置游戏状态，用于获取新谜语时
     */
    private void resetGameState() {
        currentRiddleAnswer = "";
        hintLevel = 0;
        revealedAnswerChars = null;

        binding.textViewRiddleContent.setText("正在加载谜语...");
        binding.editTextUserGuess.setText("");
        binding.editTextUserGuess.setEnabled(true);
        binding.textViewRiddleAnswer.setVisibility(View.GONE);
        binding.textViewHintArea.setVisibility(View.GONE);
        binding.textViewHintArea.setText("");
        binding.textViewGuessFeedback.setVisibility(View.GONE);
        binding.textViewGuessFeedback.setText("");

        binding.buttonSubmitGuess.setEnabled(true);
        binding.buttonGetHint.setEnabled(true);
        binding.buttonShowAnswerDirect.setEnabled(true);
        binding.buttonShowAnswerDirect.setText("直接看谜底");
    }

    /**
     * 设置新获取到的谜语
     */
    private void setupNewRiddle(RiddleData riddle) {
        if (riddle == null || binding == null) return;
        currentRiddleAnswer = riddle.getAnswer().trim();
        binding.textViewRiddleContent.setText(riddle.getContent());
    }

    /**
     * 检查用户输入的答案
     */
    private void checkUserGuess() {
        if (binding == null || TextUtils.isEmpty(currentRiddleAnswer)) return;

        hideKeyboard();
        String userAnswer = binding.editTextUserGuess.getText().toString().trim();

        if (TextUtils.isEmpty(userAnswer)) {
            binding.textViewGuessFeedback.setText("请输入你的答案！");
            binding.textViewGuessFeedback.setTextColor(ContextCompat.getColor(this, android.R.color.holo_orange_dark));
            binding.textViewGuessFeedback.setVisibility(View.VISIBLE);
            return;
        }

        // 忽略大小写进行比较
        if (userAnswer.equalsIgnoreCase(currentRiddleAnswer)) {
            binding.textViewGuessFeedback.setText("恭喜你，猜对了！");
            binding.textViewGuessFeedback.setTextColor(ContextCompat.getColor(this, R.color.correct_green)); // 你需要在 colors.xml 定义
            binding.textViewGuessFeedback.setVisibility(View.VISIBLE);
            showFullAnswer(false); // 显示完整答案，但不算作“直接查看”
            disableGameControls();
        } else {
            binding.textViewGuessFeedback.setText("不对哦，再想想！");
            binding.textViewGuessFeedback.setTextColor(ContextCompat.getColor(this, R.color.incorrect_red)); // 你需要在 colors.xml 定义
            binding.textViewGuessFeedback.setVisibility(View.VISIBLE);
            binding.editTextUserGuess.setText(""); // 清空错误答案
        }
    }

    /**
     * 提供提示
     */
    private void provideHint() {
        if (binding == null || TextUtils.isEmpty(currentRiddleAnswer)) return;
        hideKeyboard();

        hintLevel++;
        binding.textViewHintArea.setVisibility(View.VISIBLE);

        if (hintLevel == 1) { // 第一次提示：字数
            binding.textViewHintArea.setText("提示：谜底是 " + currentRiddleAnswer.length() + " 个字。");
            revealedAnswerChars = new char[currentRiddleAnswer.length()];
            Arrays.fill(revealedAnswerChars, '_'); // 没有给出的字用下划线填充
        } else if (hintLevel - 1 <= currentRiddleAnswer.length()) { // 后续提示：逐字提示
            int charIndexToReveal = hintLevel - 2; // 第2次hint揭示第0个字，第3次揭示第1个字...

            if (charIndexToReveal < currentRiddleAnswer.length()) {
                revealedAnswerChars[charIndexToReveal] = currentRiddleAnswer.charAt(charIndexToReveal);
                StringBuilder hintText = new StringBuilder("提示：");
                for (char c : revealedAnswerChars) {
                    hintText.append(c).append(" ");
                }
                binding.textViewHintArea.setText(hintText.toString().trim());

                // 如果所有字都已提示
                if (new String(revealedAnswerChars).replace(" ", "").equalsIgnoreCase(currentRiddleAnswer.replace(" ", ""))) {
                    binding.buttonGetHint.setEnabled(false); // 禁用提示按钮
                    binding.textViewHintArea.append(" (全部提示完毕)");
                }
            }
        } else {
            // 意外错误
            binding.buttonGetHint.setEnabled(false);
        }
    }

    /**
     * 显示完整答案
     * @param isDirectShow 是否是用户点击“直接看谜底”按钮
     */
    private void showFullAnswer(boolean isDirectShow) {
        if (binding == null || TextUtils.isEmpty(currentRiddleAnswer)) return;
        binding.textViewRiddleAnswer.setText("谜底：" + currentRiddleAnswer);
        binding.textViewRiddleAnswer.setVisibility(View.VISIBLE);
        binding.textViewHintArea.setVisibility(View.GONE); // 隐藏提示区
        if(isDirectShow){
            binding.textViewGuessFeedback.setText("谜底已揭晓！");
            binding.textViewGuessFeedback.setTextColor(ContextCompat.getColor(this, android.R.color.holo_blue_dark));
            binding.textViewGuessFeedback.setVisibility(View.VISIBLE);
        }
        disableGameControls();
    }

    /**
     * 禁用游戏控制按钮和输入框（例如在答对或直接看答案后）
     */
    private void disableGameControls() {
        if (binding == null) return;
        binding.editTextUserGuess.setEnabled(false);
        binding.buttonSubmitGuess.setEnabled(false);
        binding.buttonGetHint.setEnabled(false);
        binding.buttonShowAnswerDirect.setEnabled(false); // 也禁用直接看答案按钮
        binding.buttonShowAnswerDirect.setText("谜底已揭晓");
    }


    private void handleApiErrorOnUiThread(String errorMessage) {
        runOnUiThread(() -> {
            if (binding == null) return;
            showLoadingState(false);
            binding.textViewRiddleContent.setText(errorMessage);
            Toast.makeText(RiddleActivity.this, errorMessage, Toast.LENGTH_LONG).show();
        });
    }

    private void handleBusinessError(RiddleResponse riddleResponse, String rawResponse) {
        String errorMsgToShow = "获取谜语失败";
        String logMessage = "API 业务错误";

        if (riddleResponse != null) {
            logMessage += " - Code: " + riddleResponse.getCode();
            if (!TextUtils.isEmpty(riddleResponse.getMsg())) { // API 返回的是 message
                logMessage += ", Message: " + riddleResponse.getMsg();
            }

            switch (riddleResponse.getCode()) {
                case 429:
                    errorMsgToShow = "请求太频繁了，请稍后再试！";
                    break;
                case 500:
                    errorMsgToShow = "服务器开小差了，请稍后再试。";
                    break;
                case 401: // 假设 Token 错误
                    errorMsgToShow = "授权失败，请检查 Token。";
                    break;
                default:
                    if (!TextUtils.isEmpty(riddleResponse.getMsg())) {
                        errorMsgToShow += ": " + riddleResponse.getMsg();
                    } else {
                        errorMsgToShow += " (未知错误码: " + riddleResponse.getCode() + ")";
                    }
                    break;
            }
        } else {
            logMessage += " - 响应对象为 null。";
            errorMsgToShow += " (无法解析响应)";
        }
        Log.e(TAG, logMessage + " | 原始响应: " + rawResponse);
        binding.textViewRiddleContent.setText(errorMsgToShow);
        Toast.makeText(RiddleActivity.this, errorMsgToShow, Toast.LENGTH_LONG).show();
    }

    private void showLoadingState(boolean isLoading) {
        if (binding == null) return;
        binding.progressBarRiddle.setVisibility(isLoading ? View.VISIBLE : View.GONE);
        binding.buttonRefreshRiddle.setEnabled(!isLoading);
        binding.buttonSubmitGuess.setEnabled(!isLoading);
        binding.buttonGetHint.setEnabled(!isLoading);
        binding.buttonShowAnswerDirect.setEnabled(!isLoading);
        binding.editTextUserGuess.setEnabled(!isLoading); // 加载时也禁用输入
    }

    private void hideKeyboard() {
        View view = this.getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        }
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }
}
